package com.africanmoviesmobile.ui;


import java.io.IOException;
import java.util.Hashtable;

import org.pixmob.httpclient.HttpClientException;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.africanmoviesmobile.R;
import com.africanmoviesmobile.webservice.AmmWebService;
import com.africanmoviesmobile.webservice.BasicAsyncCallback;
import com.africanmoviesmobile.webservice.WebServiceException;
import com.africanmoviesmobile.webservice.inf.Movie;
import com.africanmoviesmobile.webservice.inf.User;
import com.africanmoviesmobile.webservice.inf.WebserviceObject;

public class BaseActivity extends SherlockFragmentActivity {

	//App version
	public static final String APP_VERSION = "1.2.1";
	//Site URL
    public static final String SITE_URL = "http://www.africanmoviesmobile.com";
	//URL for purchasing movie token
    public static final String BUT_TOKEN_URL = SITE_URL + "/token/pricing";
    //URL for Terms Of Service
    public static final String TOS_URL = SITE_URL + "/legal";
    //App Support Email
    public static final String APP_SUPPORT_EMAIL = "support@africanmoviesmobile.com";
       
	//cache directories
	public static final String CACHE_DIR_THUMBNAIL = "thumbnail";
	public static final String CACHE_DIR_FULL = "full_images";
	public static final String CACHE_DIR_PAGER_THUMBNAIL = "pager_thumbnail";
	public static final String CACHE_DIR_PAGER = "pager_images";
	public static final String CACHE_DIR_LATEST_MOVIES_COVER = "latest_movies_cover";
	public static final String CACHE_DIR_LATEST_MOVIES_SCREENSHOT = "latest_movies_screenshot";
	public static final String CACHE_DIR_LATEST_TOP_MOVIES_COVER = "top_rated_movie_cover";
	
	public static final String PREFS_USER_LOGIN = "USER_LOGIN";
	
	protected SharedPreferences mPrefsUserLogin = null;
	
	private KillReceiver mKillReceiver;
	
	protected int mActionBarHeight = 0;
	
	public int[] mRatingsStarDarkArray = new int[]{
    		R.drawable.rating_0_star,
    		R.drawable.rating_1_star,
    		R.drawable.rating_2_star,
    		R.drawable.rating_3_star,
    		R.drawable.rating_4_star,
    		R.drawable.rating_5_star
    };
	
	
    
    private final class KillReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    }
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		ActionBar actionBar = getSupportActionBar();
		
		actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_bg));
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayShowTitleEnabled(false);
        
		mKillReceiver = new KillReceiver();
        registerReceiver(mKillReceiver, IntentFilter.create("kill", "content://sparta"));
		
		TypedValue tv = new TypedValue();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
        	if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)){
        		mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());	
        	}
        }else{
        	if(getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true)){
        		mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
        	}
        }
        
        mPrefsUserLogin = getSharedPreferences(PREFS_USER_LOGIN, 0);
        
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getSupportMenuInflater().inflate(R.menu.base, menu);
		return true;
	}
	
	@Override
    protected void onResume() {
        super.onResume();
    }
	
	@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mKillReceiver);
    }
	
	public void logout(){
		
        if (mPrefsUserLogin != null) {
        	
        	mPrefsUserLogin.edit().clear().commit();
        	
        	mPrefsUserLogin = null;
        	
        	Intent intent = new Intent("kill");
        	intent.setType("content://sparta");
        	sendBroadcast(intent);
        	
        	startActivity(new Intent(this, LoginActivity.class));
        }
	}
	
	/**
	 * Get login email address
	 */
	public String getLoginEmail() {
		if(mPrefsUserLogin != null){
			return (String) mPrefsUserLogin.getString("email", null);
		}else{
			return null;
		}
	}
	
	/**
	 * Get login name
	 */
	public String getLoginName() {
		if(mPrefsUserLogin != null){
			return (String) mPrefsUserLogin.getString("name", null);
		}else{
			return null;
		}
	}
	
	protected void updateUserInfo(final String email, final String password, final String name){
		
		new Thread() {
			public void run() {
				
				User userInfo = null;
				
				try {
					userInfo = (User) AmmWebService.getInstance(BaseActivity.this).getUser(email);
				} catch (HttpClientException e) {
					Log.w("AMM HttpClientException:", e.getMessage());
				} catch (IOException e) {
					Log.w("AMM IOException:", e.getMessage());
				} catch (WebServiceException e) {
					Log.w("AMM WebServiceException:", e.getMessage());
				}
				
				if(userInfo != null){
					
					//update user information
					Hashtable<String, String> data = new Hashtable<String, String>();
					data.put("name", name);
					if(password != null){
						data.put("password", password);
					}
					
					try {
						userInfo.updateInfo(data);
					} catch (HttpClientException e) {
						Log.w("AMM HttpClientException:", e.getMessage());
					} catch (IOException e) {
						Log.w("AMM IOException:", e.getMessage());
					} catch (WebServiceException e) {
						Log.w("AMM WebServiceException:", e.getMessage());
						toastMessage(e.getMessage());
					}
				}else{
					
					//first time the user is logging in - add user to our database
					Hashtable<String, String> data = new Hashtable<String, String>();
					data.put("email", email);
					data.put("password", password);
					data.put("name", name);
					
					try {
						AmmWebService.getInstance(BaseActivity.this).addUser(data);
					} catch (HttpClientException e) {
						Log.w("AMM HttpClientException:", e.getMessage());
					} catch (IOException e) {
						Log.w("AMM IOException:", e.getMessage());
					} catch (WebServiceException e) {
						Log.w("AMM WebServiceException:", e.getMessage());
						toastMessage(e.getMessage());
					}
					
				}
					
					
				
			};
		}.start();
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
	        case android.R.id.home:
	            Intent intent = new Intent(this, HomeActivity.class);
	            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	            startActivity(intent);
	            return true;
	        case R.id.menu_search:
	            onSearchRequested();
	            return true;    
	        case R.id.menu_movies:
	        	startActivity(new Intent(this, MovieListActivity.class));
	            return true;    
	        case R.id.menu_celebs:
	        	startActivity(new Intent(this, CelebListActivity.class));
	            return true;
	        case R.id.menu_wishlist:
	        	startActivity(new Intent(this, WishlistActivity.class));
	            return true;
	        case R.id.menu_playlist:
	        	startActivity(new Intent(this, PlaylistActivity.class));
	            return true;   
	        case R.id.menu_token:
	        	startActivity(new Intent(this, TokenActivity.class));
	            return true;   
	        case R.id.menu_requests:
	        	startActivity(new Intent(this, RequestsActivity.class));
	            return true; 
	        case R.id.menu_sign_out:
	        	logout();
	            return true;
	        case R.id.menu_about:
	        	startActivity(new Intent(this, AboutActivity.class));
	            return true;        
	       }
		return super.onOptionsItemSelected(item);
    }
	
	public void toastMessage(final String message){
		runOnUiThread(new Runnable() {public void run() { 
			Toast.makeText(BaseActivity.this, message, Toast.LENGTH_LONG).show(); 
		}});
	}
	
	public void toastMessage(final int resId){
        runOnUiThread(new Runnable() {public void run() {   
        	        	
        	LayoutInflater inflater = getLayoutInflater();
        	View toastLayout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

    		TextView toastText = (TextView) toastLayout.findViewById(R.id.toast_text);
    		toastText.setText(resId);
    		
            Toast toast = new Toast(BaseActivity.this);
            toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, mActionBarHeight);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setView(toastLayout);
            toast.show();
            
		}});
	}
	
	public void alertMessage(final int resId){
		runOnUiThread(new Runnable() {public void run() { 
			new AlertDialog.Builder(BaseActivity.this)
            .setMessage(resId)
            .setPositiveButton(R.string.ok, null)
            .show(); 
		}});
	}
	
	public void alertMessage(final String message){
		runOnUiThread(new Runnable() {public void run() { 
			new AlertDialog.Builder(BaseActivity.this)
            .setMessage(message)
            .setPositiveButton(R.string.ok, null)
            .show(); 
		}});
	}
	
	protected void addWishlist(final int movieId, final User user){
		
		toastMessage(R.string.wishlist_adding_toast);
		
		new Thread() {
			public void run() {
				
				User userInfo = null;
				
				if(user != null){
					userInfo = user;
				}else{
					try {
						userInfo = (User) AmmWebService.getInstance(BaseActivity.this).getUser(getLoginEmail());
					} catch (HttpClientException e) {
						Log.w("AMM HttpClientException:", e.getMessage());
					} catch (IOException e) {
						Log.w("AMM IOException:", e.getMessage());
					} catch (WebServiceException e) {
						Log.w("AMM WebServiceException:", e.getMessage());
						toastMessage(R.string.user_info_error);
					}
				}
				
				if(userInfo != null){
					
					//check if the movie is already in user Wishlist
					
					boolean inWishlist = false;
					
					try {
										
						inWishlist = userInfo.movieInWishlist(movieId);
						
					} catch (HttpClientException e) {
						Log.w("AMM HttpClientException:", e.getMessage());
					} catch (IOException e) {
						Log.w("AMM IOException:", e.getMessage());
					} catch (WebServiceException e) {
						Log.w("AMM WebServiceException:", e.getMessage());
						toastMessage(e.getMessage());
					}
					
					if(inWishlist){
						toastMessage(R.string.wishlist_added_toast);
					}else{
					
						try {
														
							boolean response = userInfo.addWishlist(movieId);
							
							if (response == true) {
								toastMessage(R.string.wishlist_added_toast);
							} else {
								toastMessage(R.string.wishlist_adding_error_toast);
							}
							
						} catch (HttpClientException e) {
							Log.w("AMM HttpClientException:", e.getMessage());
						} catch (IOException e) {
							Log.w("AMM IOException:", e.getMessage());
						} catch (WebServiceException e) {
							Log.w("AMM WebServiceException:", e.getMessage());
							toastMessage(e.getMessage());
						}
					}
					
				}
				
			};
		}.start();
	}
	
	protected void deleteWishlist(final int movieId, final User user){
		
		toastMessage(R.string.wishlist_removing_toast);
		
		new Thread() {
			public void run() {
				
				User userInfo = null;
				
				if(user != null){
					userInfo = user;
				}else{
					try {
						userInfo = (User) AmmWebService.getInstance(BaseActivity.this).getUser(getLoginEmail());
					} catch (HttpClientException e) {
						Log.w("AMM HttpClientException:", e.getMessage());
					} catch (IOException e) {
						Log.w("AMM IOException:", e.getMessage());
					} catch (WebServiceException e) {
						Log.w("AMM WebServiceException:", e.getMessage());
						toastMessage(R.string.user_info_error);
					}
				}
				
				if(userInfo != null){
					
					try {
												
						boolean response = userInfo.deleteWishlist(movieId);
						
						if (response == true) {
							toastMessage(R.string.wishlist_removed_toast);
						} else {
							toastMessage(R.string.wishlist_removing_error_toast);
						}
						
					} catch (HttpClientException e) {
						Log.w("AMM HttpClientException:", e.getMessage());
					} catch (IOException e) {
						Log.w("AMM IOException:", e.getMessage());
					} catch (WebServiceException e) {
						Log.w("AMM WebServiceException:", e.getMessage());
						toastMessage(e.getMessage());
					}
					
				}
				
			};
		}.start();
	}

	protected void addPlaylist(final int movieId, final User user){
		
		toastMessage(R.string.playlist_adding_toast);
		
		new Thread() {
			public void run() {
				
				User userInfo = null;
				
				if(user != null){
					userInfo = user;
				}else{
					try {
						userInfo = (User) AmmWebService.getInstance(BaseActivity.this).getUser(getLoginEmail());
					} catch (HttpClientException e) {
						Log.w("AMM HttpClientException:", e.getMessage());
					} catch (IOException e) {
						Log.w("AMM IOException:", e.getMessage());
					} catch (WebServiceException e) {
						Log.w("AMM WebServiceException:", e.getMessage());
						toastMessage(R.string.user_info_error);
					}
				}
				
				if(userInfo != null){
					
					int tokenBalance = 0;
					
					try {
						tokenBalance = AmmWebService.getInstance(BaseActivity.this).getUserTokenBalance(getLoginEmail());
					} catch (HttpClientException e) {
						Log.w("AMM HttpClientException:", e.getMessage());
					} catch (IOException e) {
						Log.w("AMM IOException:", e.getMessage());
					} catch (WebServiceException e) {
						Log.w("AMM WebServiceException:", e.getMessage());
						toastMessage(e.getMessage());
					}
					
					if(tokenBalance > 0){
						
						//check if the movie is already in user Playlist
						
						boolean inPlaylist = false;
						
						try {
											
							inPlaylist = userInfo.movieInPlaylist(movieId);
							
						} catch (HttpClientException e) {
							Log.w("AMM HttpClientException:", e.getMessage());
						} catch (IOException e) {
							Log.w("AMM IOException:", e.getMessage());
						} catch (WebServiceException e) {
							Log.w("AMM WebServiceException:", e.getMessage());
							toastMessage(e.getMessage());
						}
						
						if(inPlaylist){

							runOnUiThread(new Runnable() {public void run() { 
								
								new AlertDialog.Builder(BaseActivity.this)
			                    .setMessage(R.string.playlist_added_toast)
			                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										playMovie(movieId, R.string.play);
									}
								})
			                    .setNegativeButton(R.string.no, null)
			                    .show();
								
							}});

						}else{
							try {
																
								boolean response = userInfo.addPlaylist(movieId);
								
								if (response == true) {
																
									runOnUiThread(new Runnable() {public void run() { 
										
										new AlertDialog.Builder(BaseActivity.this)
					                    .setMessage(R.string.playlist_added_toast)
					                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
											@Override
											public void onClick(DialogInterface dialog, int which) {
												playMovie(movieId, R.string.play);
											}
										})
					                    .setNegativeButton(R.string.no, null)
					                    .show();
										
									}});
									
								} else {
									toastMessage(R.string.playlist_adding_error_toast);
								}
														
							} catch (HttpClientException e) {
								Log.w("AMM HttpClientException:", e.getMessage());
							} catch (IOException e) {
								Log.w("AMM IOException:", e.getMessage());
							} catch (WebServiceException e) {
								Log.w("AMM WebServiceException:", e.getMessage());
								toastMessage(e.getMessage());
							}
						}
						
					}else{
						toastMessage(R.string.insufficient_token_toast);
					}
				}
				
			};
		}.start();
		
	}

	protected void playVideo(String url){
		final Intent intent = new Intent(BaseActivity.this, VideoPlayer.class);
		intent.putExtra(VideoPlayer.EXTRA_VIDEO_URL, url);
        startActivity(intent);
	}
	
	public void playMovie(final int movieId, final int type){
		
		toastMessage(R.string.loading);
		
		AmmWebService.getInstance(BaseActivity.this).getMovie(movieId, new BasicAsyncCallback() {

			public void onComplete(final WebserviceObject[] result, final Object state) {
				
				Movie movieInfo = (Movie) result[0];		

				if ((movieInfo != null)) {
					
					switch (type) {
					case R.string.preview:
						
						playVideo(movieInfo.getPreviewCdnUrl());
						
						break;
			
					case R.string.play:
						
						User userInfo = null;
						
						try {
							userInfo = (User) AmmWebService.getInstance(BaseActivity.this).getUser(getLoginEmail());
						} catch (HttpClientException e) {
							Log.w("AMM HttpClientException:", e.getMessage());
						} catch (IOException e) {
							Log.w("AMM IOException:", e.getMessage());
						} catch (WebServiceException e) {
							Log.w("AMM WebServiceException:", e.getMessage());
							toastMessage(R.string.user_info_error);
						}
						
						if(userInfo != null){
						
							boolean inPlaylist = false;
							
							try {
												
								inPlaylist = userInfo.movieInPlaylist(movieId);
								
							} catch (HttpClientException e) {
								Log.w("AMM HttpClientException:", e.getMessage());
							} catch (IOException e) {
								Log.w("AMM IOException:", e.getMessage());
							} catch (WebServiceException e) {
								Log.w("AMM WebServiceException:", e.getMessage());
								toastMessage(e.getMessage());
							}
							
							if(!inPlaylist){
								toastMessage(R.string.add_to_playlist_first);
							}else{
								playVideo(movieInfo.getCdnUrl());
							}	
						}
						
						break;
					}
				}
			}

			public void onHttpClientException(final HttpClientException e, final Object state) {
				Log.w("AMM HttpClientException:", e.getMessage());
			}
			
			public void onIOException(final IOException e, final Object state) {
				Log.w("AMM IOException:", e.getMessage());
			}

			public void onWebServiceException(final WebServiceException e, final Object state) {
				Log.w("AMM WebServiceException:", e.getMessage());
				toastMessage(e.getMessage());
			}

		}, null);
		
		
	}
}
